package top.wilbert.collegelink.message.component;

import com.alibaba.fastjson.JSON;
import top.wilbert.collegelink.message.dto.ChatMessageDto;
import top.wilbert.collegelink.message.service.ChatService;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description:
 * @Author:Jiiangyu
 * @CreatTime:2023-03-01-9:48
 */

public class MyServerSocket {

    private static final int PORT = 50000;//服务端要监听的端口
    private static Map<Long, Socket> clientMap = new HashMap<>();//为实现群聊功能而保存客户端列表
    private static ServerSocket server = null;//服务器端
    public static BufferedReader bufferedReader;
    private static ExecutorService clientES = null;//线程池，一个连接请求开始一个线程

    private static String chatMessageJson;
    private static ChatService chatService;

    public static void main(String[] args) {
        try {
            server = new ServerSocket(PORT);//服务端绑定端口PORT
            clientES = Executors.newCachedThreadPool();//创建一个可缓存线程池
            System.out.println("server is running");

            while (true) {
                Socket client = server.accept();//等待客户端的连接。这是一个阻塞函数。
                System.out.println("Accept new connection from " + client.getPort());
                //获取客户端信息
                bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
                chatMessageJson = bufferedReader.readLine();

                ChatMessageDto chatMessageDto = (ChatMessageDto) JSON.parse(chatMessageJson);
                System.out.println(chatMessageDto.toString());

                clientMap.put(chatMessageDto.getFromUserId(), client);//加入客户端列表

                clientES.execute(new ServerRunnable(client, clientMap));//连接后开启线程，进行socket通信
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class ServerRunnable implements Runnable {
        private Socket client;
        private static Map<Long, Socket> clientMap;//为实现群聊功能而保存客户端列表


        public ServerRunnable(Socket client, Map<Long, Socket> clientMap) {
            this.client = client;
            this.clientMap = clientMap;
        }

        @Override
        public void run() {
            DataInputStream input;
            DataOutputStream output;
            //获取客户端信息
            try {
                input = new DataInputStream(client.getInputStream());

                String receive = null;
                String send = null;
                ChatMessageDto chatMessageDto;

                while (true) {
                    if (!client.isClosed()) {
                        receive = input.readUTF();
                        send = receive;

                        chatMessageDto = (ChatMessageDto) JSON.parse(receive);
                        System.out.println(chatMessageDto.toString());

                        Long toUserId = chatMessageDto.getToUserId();
                        Socket toSocket = clientMap.get(toUserId);

                        if (toSocket != null) {
                            output = new DataOutputStream(toSocket.getOutputStream());
                            output.writeUTF(send);
                            output.flush();
                        }
                    }
                }
//                bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8"));
//                chatMessageJson = bufferedReader.readLine();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
